import { createRouter, createWebHistory } from 'vue-router'
import Login from '../views/Login.vue'
import SimpleLogin from '../views/SimpleLogin.vue'
import Dashboard from '../views/Dashboard.vue'
import GenerateKeys from '../views/GenerateKeys.vue'
import KeyList from '../views/KeyList.vue'
import KeyDetail from '../views/KeyDetail.vue'
import NotFound from '../views/NotFound.vue'

// 路由配置
const routes = [
  { path: '/', redirect: '/dashboard' },
  { path: '/login', name: 'Login', component: Login },
  { path: '/simple-login', name: 'SimpleLogin', component: SimpleLogin },
  { path: '/dashboard', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true } },
  { path: '/generate', name: 'GenerateKeys', component: GenerateKeys, meta: { requiresAuth: true } },
  { path: '/keys', name: 'KeyList', component: KeyList, meta: { requiresAuth: true } },
  { path: '/keys/:id', name: 'KeyDetail', component: KeyDetail, meta: { requiresAuth: true } },
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const isAuthenticated = localStorage.getItem('token')
  if (to.matched.some(record => record.meta.requiresAuth) && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router